<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'design:visa:pmVisa:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="50%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsDesignVisaPmVisaForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { PmVisa, pmVisaSave, pmVisaForm } from '/@/api/design/visa/pmVisa';
  import { pmProjectinformationTreeData } from '/@/api/proj/info/pmProjectinformation';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('design.visa.pmVisa');
  const { showMessage } = useMessage();
  const record = ref<PmVisa>({} as PmVisa);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增签证记录') : t('编辑签证记录'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('项目名称'),
      field: 'projectcode',
      fieldLabel: 'name',
      component: 'TreeSelect',
      componentProps: {
        api: pmProjectinformationTreeData,
        params: { treeOper: '16' },
        canSelectParent: false,
        allowClear: false,
      },
      itemProps: { validateTrigger: 'blur' },
      required: true,
    },
    {
      label: t('项目编号'),
      field: 'projectcode',
      component: 'Input',
      componentProps: {
        maxlength: 50,
        readonly: true,
      },
      required: true,
    },
    {
      label: t('上传人'),
      field: 'operator',
      component: 'Input',
      componentProps: {
        maxlength: 50,
        readonly: true,
      },
      required: true,
    },
    {
      label: t('签证类型'),
      field: 'istemporary',
      component: 'RadioGroup',
      componentProps: {
        dictType: 'zf_visa_type',
      },
      rules: [{ required: true, pattern: /^\d+$/, message: t('请选择签证类型') }],
      // required: true,
    },
    {
      label: t('签证描述'),
      field: 'describe',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
        rows: 3,
      },
      required: true,
    },
    {
      label: t('签证照片'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'PmVisaQz_image',
        uploadType: 'image',
        isPreview: true,
      },
      colProps: { lg: 24, md: 24 },
      rules: [
        { required: true },
        {
          validator(_rule, value) {
            return new Promise((resolve, reject) => {
              const len = !value || value['PmVisaQz_image__len'] || 0;
              if (len == 0) reject(t('请上传签证照片！'));
              else resolve();
            });
          },
        },
      ],
      itemProps: { validateTrigger: 'blur' },
    },
    {
      label: t('现场照片'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'PmVisaXc_image',
        uploadType: 'image',
        isPreview: true,
      },
      colProps: { lg: 24, md: 24 },
      // rules: [
      //   { required: true },
      //   {
      //     validator(_rule, value) {
      //       return new Promise((resolve, reject) => {
      //         const len = !value || value['PmVisaXc_image'] || 0;
      //         if (len == 0) reject(t('请上传现场照片！'));
      //         else resolve();
      //       });
      //     },
      //   },
      // ],
      itemProps: { validateTrigger: 'blur' },
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await pmVisaForm(data);
    record.value = (res.pmVisa || {}) as PmVisa;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      console.log('submit', data);
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
        fileid: record.value.fileid,
        scenefile: record.value.scenefile,
      };
      // console.log('submit', params, data, record);
      const res = await pmVisaSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
